`
Table 1-7
Special Variables Related to Positional Arguments
Variable
Description
$0
The name of the script file
$1, $2, $3, […]
Positional arguments
$#
The number of passed positional arguments
$*
All positional arguments
$@
All positional arguments, where each argument is individually quoted
When a script makes use of "$*" with the quotes included, bash
will expand arguments into a single word. For instance, the
following groups the arguments into one word:
$ script.sh "1" "2" "3"
1 2 3
When a script makes use of "$@" (again including the quotes), it
will expand arguments into separate words:
$ script.sh "1" "2" "3"
1
2
3
In most cases, you will want to use "$@" so that every argument
is treated as an individual word.
Input Prompting
Some bash scripts don’t take any arguments during execution.
However, they may need to ask the user for some information in an
interactive way and have the response feed into their runtime. In
these cases, we can use the read command. You often see
applications use input prompting when attempting to install some
software, asking the user to enter yes to proceed or no to cancel the
operation.
In the following bash script, we ask the user for their first and
last name, then print these to the standard output stream.
#!/bin/bash
# Takes input from the user and assigns it to variables.
echo "What is your first name?"
read -r firstname
echo "What is your last name?"
read -r lastname
echo "Your first name is ${firstname} and your last name is ${lastname}"
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks